package com.jn.zhinongbao.adapter.provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import com.example.supportingagriculturaltreasures.database.DatabaseHelper;

public class AgriculturalContentProvider extends ContentProvider {

    // 授权
    public static final String AUTHORITY = "com.example.supportingagriculturaltreasures.provider";
    
    // 基础URI
    public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
    
    // 路径
    public static final String PATH_PRODUCTS = "products";
    public static final String PATH_PURCHASES = "purchases";
    public static final String PATH_ORDERS = "orders";
    public static final String PATH_CART = "cart";
    public static final String PATH_NEWS = "news";
    public static final String PATH_FARMER_CIRCLE = "farmer_circle";
    public static final String PATH_CHAT_ROOMS = "chat_rooms";
    public static final String PATH_CHAT_MESSAGES = "chat_messages";
    
    // URI
    public static final Uri CONTENT_URI_PRODUCTS = BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRODUCTS).build();
    public static final Uri CONTENT_URI_PURCHASES = BASE_CONTENT_URI.buildUpon().appendPath(PATH_PURCHASES).build();
    public static final Uri CONTENT_URI_ORDERS = BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORDERS).build();
    public static final Uri CONTENT_URI_CART = BASE_CONTENT_URI.buildUpon().appendPath(PATH_CART).build();
    public static final Uri CONTENT_URI_NEWS = BASE_CONTENT_URI.buildUpon().appendPath(PATH_NEWS).build();
    public static final Uri CONTENT_URI_FARMER_CIRCLE = BASE_CONTENT_URI.buildUpon().appendPath(PATH_FARMER_CIRCLE).build();
    public static final Uri CONTENT_URI_CHAT_ROOMS = BASE_CONTENT_URI.buildUpon().appendPath(PATH_CHAT_ROOMS).build();
    public static final Uri CONTENT_URI_CHAT_MESSAGES = BASE_CONTENT_URI.buildUpon().appendPath(PATH_CHAT_MESSAGES).build();
    
    // URI匹配器
    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    
    // 匹配码
    private static final int PRODUCTS = 100;
    private static final int PRODUCT_ID = 101;
    private static final int PURCHASES = 200;
    private static final int PURCHASE_ID = 201;
    private static final int ORDERS = 300;
    private static final int ORDER_ID = 301;
    private static final int CART = 400;
    private static final int CART_ID = 401;
    private static final int NEWS = 500;
    private static final int NEWS_ID = 501;
    private static final int FARMER_CIRCLE = 600;
    private static final int FARMER_CIRCLE_ID = 601;
    private static final int CHAT_ROOMS = 700;
    private static final int CHAT_ROOM_ID = 701;
    private static final int CHAT_MESSAGES = 800;
    private static final int CHAT_MESSAGE_ID = 801;
    
    static {
        sUriMatcher.addURI(AUTHORITY, PATH_PRODUCTS, PRODUCTS);
        sUriMatcher.addURI(AUTHORITY, PATH_PRODUCTS + "/#", PRODUCT_ID);
        sUriMatcher.addURI(AUTHORITY, PATH_PURCHASES, PURCHASES);
        sUriMatcher.addURI(AUTHORITY, PATH_PURCHASES + "/#", PURCHASE_ID);
        sUriMatcher.addURI(AUTHORITY, PATH_ORDERS, ORDERS);
        sUriMatcher.addURI(AUTHORITY, PATH_ORDERS + "/#", ORDER_ID);
        sUriMatcher.addURI(AUTHORITY, PATH_CART, CART);
        sUriMatcher.addURI(AUTHORITY, PATH_CART + "/#", CART_ID);
        sUriMatcher.addURI(AUTHORITY, PATH_NEWS, NEWS);
        sUriMatcher.addURI(AUTHORITY, PATH_NEWS + "/#", NEWS_ID);
        sUriMatcher.addURI(AUTHORITY, PATH_FARMER_CIRCLE, FARMER_CIRCLE);
        sUriMatcher.addURI(AUTHORITY, PATH_FARMER_CIRCLE + "/#", FARMER_CIRCLE_ID);
        sUriMatcher.addURI(AUTHORITY, PATH_CHAT_ROOMS, CHAT_ROOMS);
        sUriMatcher.addURI(AUTHORITY, PATH_CHAT_ROOMS + "/*", CHAT_ROOM_ID);
        sUriMatcher.addURI(AUTHORITY, PATH_CHAT_MESSAGES, CHAT_MESSAGES);
        sUriMatcher.addURI(AUTHORITY, PATH_CHAT_MESSAGES + "/*", CHAT_MESSAGE_ID);
    }
    
    private DatabaseHelper mDatabaseHelper;

    @Override
    public boolean onCreate() {
        mDatabaseHelper = new DatabaseHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteDatabase database = mDatabaseHelper.getReadableDatabase();
        Cursor cursor;
        
        int match = sUriMatcher.match(uri);
        switch (match) {
            case PRODUCTS:
                cursor = database.query("products", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case PRODUCT_ID:
                selection = "id=?";
                selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
                cursor = database.query("products", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case PURCHASES:
                cursor = database.query("purchases", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case PURCHASE_ID:
                selection = "id=?";
                selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
                cursor = database.query("purchases", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case ORDERS:
                cursor = database.query("orders", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case ORDER_ID:
                selection = "id=?";
                selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
                cursor = database.query("orders", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case CART:
                cursor = database.query("cart", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case CART_ID:
                selection = "id=?";
                selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
                cursor = database.query("cart", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case NEWS:
                cursor = database.query("news", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case NEWS_ID:
                selection = "id=?";
                selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
                cursor = database.query("news", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case FARMER_CIRCLE:
                cursor = database.query("farmer_circle", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case FARMER_CIRCLE_ID:
                selection = "id=?";
                selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
                cursor = database.query("farmer_circle", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case CHAT_ROOMS:
                cursor = database.query("chat_rooms", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case CHAT_ROOM_ID:
                selection = "id=?";
                selectionArgs = new String[]{uri.getLastPathSegment()};
                cursor = database.query("chat_rooms", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case CHAT_MESSAGES:
                cursor = database.query("chat_messages", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case CHAT_MESSAGE_ID:
                selection = "id=?";
                selectionArgs = new String[]{uri.getLastPathSegment()};
                cursor = database.query("chat_messages", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        int match = sUriMatcher.match(uri);
        switch (match) {
            case PRODUCTS:
                return "vnd.android.cursor.dir/vnd." + AUTHORITY + "." + PATH_PRODUCTS;
            case PRODUCT_ID:
                return "vnd.android.cursor.item/vnd." + AUTHORITY + "." + PATH_PRODUCTS;
            case PURCHASES:
                return "vnd.android.cursor.dir/vnd." + AUTHORITY + "." + PATH_PURCHASES;
            case PURCHASE_ID:
                return "vnd.android.cursor.item/vnd." + AUTHORITY + "." + PATH_PURCHASES;
            case ORDERS:
                return "vnd.android.cursor.dir/vnd." + AUTHORITY + "." + PATH_ORDERS;
            case ORDER_ID:
                return "vnd.android.cursor.item/vnd." + AUTHORITY + "." + PATH_ORDERS;
            case CART:
                return "vnd.android.cursor.dir/vnd." + AUTHORITY + "." + PATH_CART;
            case CART_ID:
                return "vnd.android.cursor.item/vnd." + AUTHORITY + "." + PATH_CART;
            case NEWS:
                return "vnd.android.cursor.dir/vnd." + AUTHORITY + "." + PATH_NEWS;
            case NEWS_ID:
                return "vnd.android.cursor.item/vnd." + AUTHORITY + "." + PATH_NEWS;
            case FARMER_CIRCLE:
                return "vnd.android.cursor.dir/vnd." + AUTHORITY + "." + PATH_FARMER_CIRCLE;
            case FARMER_CIRCLE_ID:
                return "vnd.android.cursor.item/vnd." + AUTHORITY + "." + PATH_FARMER_CIRCLE;
            case CHAT_ROOMS:
                return "vnd.android.cursor.dir/vnd." + AUTHORITY + "." + PATH_CHAT_ROOMS;
            case CHAT_ROOM_ID:
                return "vnd.android.cursor.item/vnd." + AUTHORITY + "." + PATH_CHAT_ROOMS;
            case CHAT_MESSAGES:
                return "vnd.android.cursor.dir/vnd." + AUTHORITY + "." + PATH_CHAT_MESSAGES;
            case CHAT_MESSAGE_ID:
                return "vnd.android.cursor.item/vnd." + AUTHORITY + "." + PATH_CHAT_MESSAGES;
            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase database = mDatabaseHelper.getWritableDatabase();
        Uri returnUri;
        
        int match = sUriMatcher.match(uri);
        switch (match) {
            case PRODUCTS:
                long productId = database.insert("products", null, values);
                if (productId > 0) {
                    returnUri = ContentUris.withAppendedId(CONTENT_URI_PRODUCTS, productId);
                } else {
                    throw new android.database.SQLException("Failed to insert row into " + uri);
                }
                break;
            case PURCHASES:
                long purchaseId = database.insert("purchases", null, values);
                if (purchaseId > 0) {
                    returnUri = ContentUris.withAppendedId(CONTENT_URI_PURCHASES, purchaseId);
                } else {
                    throw new android.database.SQLException("Failed to insert row into " + uri);
                }
                break;
            case ORDERS:
                long orderId = database.insert("orders", null, values);
                if (orderId > 0) {
                    returnUri = ContentUris.withAppendedId(CONTENT_URI_ORDERS, orderId);
                } else {
                    throw new android.database.SQLException("Failed to insert row into " + uri);
                }
                break;
            case CART:
                long cartId = database.insert("cart", null, values);
                if (cartId > 0) {
                    returnUri = ContentUris.withAppendedId(CONTENT_URI_CART, cartId);
                } else {
                    throw new android.database.SQLException("Failed to insert row into " + uri);
                }
                break;
            case NEWS:
                long newsId = database.insert("news", null, values);
                if (newsId > 0) {
                    returnUri = ContentUris.withAppendedId(CONTENT_URI_NEWS, newsId);
                } else {
                    throw new android.database.SQLException("Failed to insert row into " + uri);
                }
                break;
            case FARMER_CIRCLE:
                long farmerCircleId = database.insert("farmer_circle", null, values);
                if (farmerCircleId > 0) {
                    returnUri = ContentUris.withAppendedId(CONTENT_URI_FARMER_CIRCLE, farmerCircleId);
                } else {
                    throw new android.database.SQLException("Failed to insert row into " + uri);
                }
                break;
            case CHAT_ROOMS:
                long chatRoomResult = database.insert("chat_rooms", null, values);
                if (chatRoomResult > 0) {
                    returnUri = CONTENT_URI_CHAT_ROOMS.buildUpon()
                            .appendPath(values.getAsString("id")).build();
                } else {
                    throw new android.database.SQLException("Failed to insert row into " + uri);
                }
                break;
            case CHAT_MESSAGES:
                long chatMessageResult = database.insert("chat_messages", null, values);
                if (chatMessageResult > 0) {
                    returnUri = CONTENT_URI_CHAT_MESSAGES.buildUpon()
                            .appendPath(values.getAsString("id")).build();
                } else {
                    throw new android.database.SQLException("Failed to insert row into " + uri);
                }
                break;
            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
        
        getContext().getContentResolver().notifyChange(uri, null);
        return returnUri;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase database = mDatabaseHelper.getWritableDatabase();
        int rowsDeleted;
        
        int match = sUriMatcher.match(uri);
        switch (match) {
            case PRODUCTS:
                rowsDeleted = database.delete("products", selection, selectionArgs);
                break;
            case PRODUCT_ID:
                String productId = uri.getPathSegments().get(1);
                rowsDeleted = database.delete("products", "id=?", new String[]{productId});
                break;
            case PURCHASES:
                rowsDeleted = database.delete("purchases", selection, selectionArgs);
                break;
            case PURCHASE_ID:
                String purchaseId = uri.getPathSegments().get(1);
                rowsDeleted = database.delete("purchases", "id=?", new String[]{purchaseId});
                break;
            case ORDERS:
                rowsDeleted = database.delete("orders", selection, selectionArgs);
                break;
            case ORDER_ID:
                String orderId = uri.getPathSegments().get(1);
                rowsDeleted = database.delete("orders", "id=?", new String[]{orderId});
                break;
            case CART:
                rowsDeleted = database.delete("cart", selection, selectionArgs);
                break;
            case CART_ID:
                String cartId = uri.getPathSegments().get(1);
                rowsDeleted = database.delete("cart", "id=?", new String[]{cartId});
                break;
            case NEWS:
                rowsDeleted = database.delete("news", selection, selectionArgs);
                break;
            case NEWS_ID:
                String newsId = uri.getPathSegments().get(1);
                rowsDeleted = database.delete("news", "id=?", new String[]{newsId});
                break;
            case FARMER_CIRCLE:
                rowsDeleted = database.delete("farmer_circle", selection, selectionArgs);
                break;
            case FARMER_CIRCLE_ID:
                String farmerCircleId = uri.getPathSegments().get(1);
                rowsDeleted = database.delete("farmer_circle", "id=?", new String[]{farmerCircleId});
                break;
            case CHAT_ROOMS:
                rowsDeleted = database.delete("chat_rooms", selection, selectionArgs);
                break;
            case CHAT_ROOM_ID:
                String chatRoomId = uri.getPathSegments().get(1);
                rowsDeleted = database.delete("chat_rooms", "id=?", new String[]{chatRoomId});
                break;
            case CHAT_MESSAGES:
                rowsDeleted = database.delete("chat_messages", selection, selectionArgs);
                break;
            case CHAT_MESSAGE_ID:
                String chatMessageId = uri.getPathSegments().get(1);
                rowsDeleted = database.delete("chat_messages", "id=?", new String[]{chatMessageId});
                break;
            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
        
        if (rowsDeleted != 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        
        return rowsDeleted;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        SQLiteDatabase database = mDatabaseHelper.getWritableDatabase();
        int rowsUpdated;
        
        int match = sUriMatcher.match(uri);
        switch (match) {
            case PRODUCTS:
                rowsUpdated = database.update("products", values, selection, selectionArgs);
                break;
            case PRODUCT_ID:
                String productId = uri.getPathSegments().get(1);
                rowsUpdated = database.update("products", values, "id=?", new String[]{productId});
                break;
            case PURCHASES:
                rowsUpdated = database.update("purchases", values, selection, selectionArgs);
                break;
            case PURCHASE_ID:
                String purchaseId = uri.getPathSegments().get(1);
                rowsUpdated = database.update("purchases", values, "id=?", new String[]{purchaseId});
                break;
            case ORDERS:
                rowsUpdated = database.update("orders", values, selection, selectionArgs);
                break;
            case ORDER_ID:
                String orderId = uri.getPathSegments().get(1);
                rowsUpdated = database.update("orders", values, "id=?", new String[]{orderId});
                break;
            case CART:
                rowsUpdated = database.update("cart", values, selection, selectionArgs);
                break;
            case CART_ID:
                String cartId = uri.getPathSegments().get(1);
                rowsUpdated = database.update("cart", values, "id=?", new String[]{cartId});
                break;
            case NEWS:
                rowsUpdated = database.update("news", values, selection, selectionArgs);
                break;
            case NEWS_ID:
                String newsId = uri.getPathSegments().get(1);
                rowsUpdated = database.update("news", values, "id=?", new String[]{newsId});
                break;
            case FARMER_CIRCLE:
                rowsUpdated = database.update("farmer_circle", values, selection, selectionArgs);
                break;
            case FARMER_CIRCLE_ID:
                String farmerCircleId = uri.getPathSegments().get(1);
                rowsUpdated = database.update("farmer_circle", values, "id=?", new String[]{farmerCircleId});
                break;
            case CHAT_ROOMS:
                rowsUpdated = database.update("chat_rooms", values, selection, selectionArgs);
                break;
            case CHAT_ROOM_ID:
                String chatRoomId = uri.getPathSegments().get(1);
                rowsUpdated = database.update("chat_rooms", values, "id=?", new String[]{chatRoomId});
                break;
            case CHAT_MESSAGES:
                rowsUpdated = database.update("chat_messages", values, selection, selectionArgs);
                break;
            case CHAT_MESSAGE_ID:
                String chatMessageId = uri.getPathSegments().get(1);
                rowsUpdated = database.update("chat_messages", values, "id=?", new String[]{chatMessageId});
                break;
            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
        
        if (rowsUpdated != 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        
        return rowsUpdated;
    }
} 